import comTitle from "@/views/com/com_title.vue";
import cropperModal from "@/components/cropper/index.vue";
import QuillEditor from "@/components/Editor/QuillEditor.vue";
import { fileBase64, toDecimal2 } from '@/util/util'
import { goodstockfetchList, getPlatformShopInfo, getPersonGradeInfoList, addIntegralGoods, updateIntegralInfo, detail } from '@/api/shop/pointsMall/pointsGoods.js'
import { upLoad } from '@/api/shop/upLoad.js'

export default {
    components: {
        comTitle,
        cropperModal,
        QuillEditor
    },
    data() {
        return {
            labelWidth: "120px",
            disabled: false,
            ruleForm: {
                shopId: [],
                iszdHuiYuanList: [],
                exchangeScope: '00',
                iszdHuiYuan: '00',
                shelfState: '01',
                goodsExchUnit: '01',
                userExchUnit: '01',
                costPrice: 0
            },
            soldOut: true, //如初始库存为0，商品上架后为售罄状态
            rules: {
                goodsName: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                    { min: 1, max: 30, message: '商品名称超过30个字符不可输入', trigger: 'blur' }
                ],
                barCode: [
                    { required: true, message: '请输入商品条码', trigger: 'blur' },
                ],
                exchangeNum: [
                    { required: true, message: '请输入所需积分', trigger: 'blur' },
                ],
                stockNum: [
                    { required: true, message: '请输入库存数量', trigger: 'blur' },
                ],
                costPrice: [
                    { required: true, message: '请输入成本价', trigger: 'blur' },
                ],
                goodsDetails: [
                    { required: true, message: '请填写商品详情', trigger: 'blur' },
                ],
                stockUnit: [
                    { required: true, message: '请选择库存单位', trigger: 'change' },
                ],
                shopId: [
                    { required: true, message: '请选择门店', trigger: 'change' },
                ],
                userExchUnit: [
                    { required: true, message: '请选择用户兑换限制', trigger: 'change' },
                ],
                goodsExchUnit: [
                    { required: true, message: '请选择商品兑换限制', trigger: 'change' },
                ],
                exchangeScope: [
                    { required: true, message: '请选择可兑换渠道', trigger: 'change' },
                ],
                shelfState: [
                    { required: true, message: '请选择商品状态', trigger: 'change' },
                ],
            },
            gysmc: [ //供应商名称
                {
                    label: "小鸟伏特加",
                    value: 1
                }
            ],
            tqList: [{
                label: "通勤",
                value: 1
            }, {
                label: "居家",
                value: 2
            },],
            jjList: [{
                label: "修身",
                value: 1
            }, {
                label: "中长款",
                value: 2
            }, {
                label: "气质",
                value: 3
            },],
            zdhyList: [ //指定会员
                {
                    label: "黄金会员",
                    value: 1
                }, {
                    label: "铂金会员",
                    value: 2
                }, {
                    label: "钻石会员",
                    value: 3
                },
            ],
            mendianList: [ //门店list
            ],
            imageUrl: "",
            loading: false, //上传
            optionsData: {
                title: "商品图片", //弹框表头
                img: '', //裁切图片地址
                autoCrop: true, //是否默认生成截图框
                autoCropWidth: 200, //默认生成截图框宽度
                autoCropHeight: 200, //默认生成截图框高度
                fixedBox: false, //固定截图框大小 不允许改变
                thumbnailName: "衣家生活"
            },
            number: 0,
            fileList: [],
            dialogImageUrl: '', //放大图片
            dialogVisible: false,
            stockUnitList: [], //库存单位
            iszdHuiYuan: [], //指定会员
            shopId: [],
            oldShop: [],  //回显商店数组
            imgUrlList: []
        }
    },
    created() {
        this.getList()
        console.log(888, this.$route.query.id)
        if (this.$route.query.id) {
            // this.ruleForm = this.$route.query
            detail(this.$route.query.id).then(val => {
                this.ruleForm = val.data.data
                console.log(888, val)

                if (this.ruleForm.distributionChannel) {
                    if (this.ruleForm.distributionChannel.length) {
                        this.ruleForm.shopId = this.ruleForm.distributionChannel.split(',')
                    }
                } else {
                    this.ruleForm.shopId = []
                }
                this.oldShop = this.ruleForm.shopId
                console.log('this.oldShop', this.oldShop)

                if (this.ruleForm.exchLimitGrade == '00') {
                    this.ruleForm.iszdHuiYuan = '00'
                    this.ruleForm.iszdHuiYuanList = []
                } else {
                    this.ruleForm.iszdHuiYuan = '01'
                    if (this.ruleForm.exchLimitGrade) {
                        this.ruleForm.iszdHuiYuanList = this.ruleForm.exchLimitGrade.split(',')

                    } else {
                        this.ruleForm.iszdHuiYuanList = []
                    }
                }
                if (this.ruleForm.exchBeginTime || this.ruleForm.exchEndTime) {  //时间回显
                    this.ruleForm.cxsj = [this.ruleForm.exchBeginTime, this.ruleForm.exchEndTime]
                }


                let pic = []            //图片回显
                if (this.ruleForm.goodsPic) {
                    if (this.ruleForm.goodsPic.indexOf(',') > -1) {
                        pic = this.ruleForm.goodsPic.split(',')
                        pic.forEach(item => {
                            this.fileList.push({ url: process.url + item, name: '商品图片' })
                            this.imgUrlList.push({ url: item, name: '商品图片' })
                        })
                    } else {
                        this.fileList.push({ url: process.url + this.ruleForm.goodsPic, name: '商品图片' })
                        this.imgUrlList.push({ url: this.ruleForm.goodsPic, name: '商品图片' })
                    }
                }

                console.log(176, this.ruleForm)
            })




        }
    },
    watch: {
        "ruleForm.iszdHuiYuan"(val) {
            if (val == '00') {
                this.ruleForm.exchLimitGrade = '00'
            }
        }
    },
    methods: {
        getList() {
            goodstockfetchList().then(val => { //库存单位
                let data = val.data.data
                console.log('库存单位', data)
                this.stockUnitList = data.records.map(item => {
                    return {
                        value: item.stockUnitId,
                        label: item.stockUnitName
                    }
                })

            })
            getPlatformShopInfo().then(val => { //获取平台下门店
                let data = val.data.data
                if (data) {
                    this.mendianList = data.map(item => {
                        return {
                            value: item.shopId,
                            label: item.provinceCode + item.cityCode + item.districtCode + item.shopName,
                        }
                    })
                    if (!this.$route.query.id) {
                        this.ruleForm.shopId = data.map(item => {
                            return item.shopId
                        })
                    }
                }

            })
            getPersonGradeInfoList().then(val => { //指定会员
                let data = val.data.data
                console.log(data)
                if (data) {
                    this.zdhyList = data.map(item => {
                        return {
                            value: item.gradeId,
                            label: item.gradeName,
                        }
                    })
                }
            })
        },
        submitSave() { //提交并保存

            console.log(this.fileList)
            if (this.ruleForm.iszdHuiYuan == '00') {
                this.ruleForm.exchLimitGrade = '00'
            } else {
                let list = [...this.ruleForm.iszdHuiYuanList]
                this.ruleForm.exchLimitGrade = list.join(',')
            }
            let urlList = [...this.imgUrlList]
            if (urlList.length) { //图片处理
                let imgList = []
                urlList.forEach(item => {
                    if (item.url.indexOf(process.url) > -1) { //截取路径
                        item.url = item.url.replace(process.url, '')
                    }
                    imgList.push(item.url)
                })
                this.ruleForm.goodsPic = imgList.join(',')
            }
            let obj = { ...this.ruleForm }
            obj.shopId = obj.shopId.join(',')
            console.log(obj)
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    addIntegralGoods(obj).then(() => {
                        this.quxiao('ruleForm')
                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        upDate() {

            if (this.ruleForm.iszdHuiYuan == '00') {
                this.ruleForm.exchLimitGrade = '00'
            } else {
                let list = [...this.ruleForm.iszdHuiYuanList]
                this.ruleForm.exchLimitGrade = list.join(',')
            }

            let urlList = [...this.imgUrlList]
            if (urlList.length) { //图片处理
                let imgList = []
                urlList.forEach(item => {
                    if (item.url.indexOf(process.url) > -1) { //截取路径
                        item.url = item.url.replace(process.url, '')
                    }
                    imgList.push(item.url)
                })
                this.ruleForm.goodsPic = imgList.join(',')
            }
            let obj = { ...this.ruleForm }
            // obj.shopId = obj.shopId.join(',')

            let newarr = []   //两个数组比较减去重复的部分  shopId新增项   
            var tmp = this.oldShop.concat(obj.shopId);
            var o = {};
            for (let i = 0; i < tmp.length; i++) {
                (tmp[i] in o) ? o[tmp[i]]++ : o[tmp[i]] = 1;
            }
            for (let x in o) {
                if (o[x] == 1) {
                    newarr.push(x);
                }
            }

            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    obj.shopId = newarr.join(',')
                    updateIntegralInfo(obj).then(() => {
                        this.quxiao('ruleForm')
                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        // save() {   //保存
        //     console.log(this.ruleForm)
        //     if (this.ruleForm.sptm == 0) {
        //         this.rules.sptm1[0].required = false; //商品条码
        //     } else {
        //         this.rules.sptm1[0].required = true;
        //     }
        //     this.$refs['ruleForm'].validate((valid) => {
        //         if (valid) {
        //             alert('submit!');
        //         } else {
        //             console.log('error submit!!');
        //             return false;
        //         }
        //     });
        // },
        quxiao(ruleForm) { //取消
            this.$router.go(-1)
            this.$refs[ruleForm].resetFields();
            this.ruleForm = {
                sptm: 0,
                kcsl: 1,
                cxsp: 0,
                mdsp: 0
            }
        },

        handleChange(file) { //上传触发
            // console.log(file)
            let { options } = this;
            // console.log(file)
            // fileBase64(file.file.originFileObj).then(result => {
            let target = Object.assign({}, options, {
                img: file.url,
                files: file
            })
            this.$refs['cropperModal'].edit(target);
            // })
        },
        beforeUpload(file) {
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
            if (!isJpgOrPng) {
                this.$message.error('图片格式不支持！');
            }
            const isLt1M = file.size / 1024 / 1024 < 1;
            if (!isLt1M) {
                this.$message.error('图片大小限制在1MB内!');
            }
            return isJpgOrPng && isLt1M;
        },
        setMaster(file) {  //设置主图
            let subFile = this.imgUrlList[this.fileList.indexOf(file)]  //找到提交的图片数组

            for (var i = 0; i < this.fileList.length; i++) {  //根据file 找到数组的位置
                if (this.fileList[i] === file) {
                    this.fileList.splice(i, 1);
                    this.imgUrlList.splice(i, 1);
                    break;
                }
            }
            this.imgUrlList.unshift(subFile);  //提交的图片
            this.fileList.unshift(file);  //回显的图片
            console.log(this.imgUrlList)
            console.log(this.fileList)
        },
        handlePictureCardPreview(file) {
            this.dialogVisible = true,
                this.dialogImageUrl = file.url
        },
        delUplod(file) {
            const index = this.fileList.indexOf(file)
            const newFileList = this.fileList.slice()
            newFileList.splice(index, 1)
            this.fileList = newFileList
            this.imgUrlList.splice(index, 1)
        },
        handleCropperSuccess(data) { //图片裁切完成保存
            upLoad(data).then(res => {
                this.imgUrlList.push(res.data.data)
                this.fileList.push({
                    uid: this.number++,
                    name: 'image.png',
                    status: 'done',
                    url: URL.createObjectURL(data)
                })
                this.$message.success('上传成功！')
            }).catch(() => {
                this.$message.warning('上传失败，请重新上传！')
            })
        },
        toDecimalBlur(name) { //保留两位小数
            // if (name === 'xsj') {
            //     this.ruleForm.xsj = toDecimal2(this.ruleForm.xsj)
            // } else if (name === 'cbj') {
            //     this.ruleForm.cbj = toDecimal2(this.ruleForm.cbj)
            // } else 
            if (name === 'kcsl') {
                console.log()
                if (this.ruleForm.kcsl < 0) {
                    this.ruleForm.kcsl = 0
                }
            }

        },
        addKchs() { //库存换算新增
            this.ruleForm.kchs.push({});
        },
        editKchs(item) { //库存换算删除
            let index = this.ruleForm.kchs.indexOf(item);
            if (index !== -1) {
                this.ruleForm.kchs.splice(index, 1);
            }
        },
        cxsjChange(e) { //促销时间
            if (e) {
                this.ruleForm.exchBeginTime = this.formDate(e[0])
                this.ruleForm.exchEndTime = this.formDate(e[1])
            } else {
                delete this.ruleForm.cxsj
            }
            console.log(this.ruleForm)
            this.$forceUpdate()
        },
        editorChange(quill, html, text) { //富文本编辑器
            console.log(quill)
            console.log(html)
            console.log(text)
            this.ruleForm.goodsDetails = html
        },


        exchangeScopeChange(e) {

        },
        removeTag(value) {
            const index = this.oldShop.indexOf(value)
            if (index !== -1) {
                this.$message({
                    message: '不允许删除已选门店！',
                    type: 'warning'
                });
                this.ruleForm.shopId.splice(index, 0, value)
            }
        }
    },

}